package com.rongcheng.frc.androidlib.net.mock;

import android.app.Activity;
import android.content.res.XmlResourceParser;

import com.rongcheng.frc.androidlib.R;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by frc on 16-6-15.
 */
public class MockConfigManager {
    private static ArrayList<MockSettingData> mocklist;


    public static MockSettingData findMockConfig(final Activity activity, final String findkey) {
        if (mocklist == null || mocklist.isEmpty()) {
            fetchMockDataFromXml(activity);
        }
        for (MockSettingData mockSetting : mocklist
                ) {
            if (findkey.equals(mockSetting.getKey())) {
                return mockSetting;
            }

        }
        return null;
    }

    private static void fetchMockDataFromXml(Activity activity) {
        mocklist = new ArrayList<MockSettingData>();
        final XmlResourceParser xmlParser = activity.getApplication().getResources().getXml(R.xml.mock);
        int eventCode;
        try {
            eventCode = xmlParser.getEventType();
            while (eventCode != XmlPullParser.END_DOCUMENT) {
                switch (eventCode) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("Node".equals(xmlParser.getName())) {
                            final MockSettingData mockSettingData = new MockSettingData();
                            mockSettingData.setKey(xmlParser.getAttributeValue(null, "key"));
                            mockSettingData.setConnectTime(Long.parseLong(xmlParser.getAttributeValue(null, "connectTime")));
                            mockSettingData.setErrorScale(Integer.valueOf(xmlParser.getAttributeValue(null, "errorScale")));
                            mockSettingData.setNetErrorScale(Integer.valueOf(xmlParser.getAttributeValue(null, "netErrorScale")));
                            mockSettingData.setSuccessScale(Integer.valueOf(xmlParser.getAttributeValue(null, "successScale")));
                            mockSettingData.setMockFile(xmlParser.getAttributeValue(null,"mockFile"));
                            mocklist.add(mockSettingData);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                eventCode = xmlParser.next();
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            xmlParser.close();
        }

    }

}
